<template>
  <el-dialog
    v-model="dialogFormVisible"
    :title="title"
    width="1600px"
    @close="close"
  >
    <el-dialog
      v-model="innerVisible"
      width="1000"
      title="任务提交详情"
      append-to-body
      top="3vh"
    >
      <div class="htmlBox" v-html="currShowSubmit.SubmitTaskMemo"></div>
    </el-dialog>
    <div>
      <el-form
        ref="formRef"
        label-width="150px"
        :model="form"
        :rules="isRules"
        style="display: flex; align-items: flex-end"
      >
        <div style="width: 80%">
          <el-form-item label="请选择产品或赠品" prop="ProductType">
            <el-select
              v-model="form.ProductType"
              :disabled="form.QuerenCount > 1"
              style="width: 100px"
              @change="form.OrderListID = null"
            >
              <el-option label="产品" :value="0" />
              <el-option label="赠品" :value="1" />
            </el-select>

            <el-select
              v-if="form.ProductType == 0"
              v-model="form.OrderListID"
              :disabled="form.QuerenCount > 1"
              style="width: 250px; margin-left: 10px"
            >
              <el-option
                v-for="item in OrderList"
                :key="item.OrderListID"
                :label="item.ProductName"
                :value="item.OrderListID"
              />
            </el-select>

            <el-select
              v-if="form.ProductType == 1"
              v-model="form.OrderListID"
              :disabled="form.QuerenCount > 1"
              style="width: 250px; margin-left: 10px"
            >
              <el-option
                v-for="item in GiftList"
                :key="item.OrderListID"
                :label="item.ProductName"
                :value="item.OrderListID"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="所属组织" prop="TaskCompany">
            <el-cascader
              v-model="form.TaskCompany"
              :disabled="flag || form.QuerenCount > 1"
              :options="organizationList"
              :props="companyProps"
              style="width: 100%"
              clearable
              @change="getDeptment"
            />
          </el-form-item>
          <el-form-item label="所属部门" prop="TaskDeptment">
            <el-cascader
              v-model="form.TaskDeptment"
              :disabled="flag || form.QuerenCount > 1"
              :options="departmentList"
              :props="deptmentProps"
              style="width: 100%"
              clearable
              @change="getStaffPost"
            />
          </el-form-item>
          <el-form-item :label="title" prop="TaskStaffID">
            <el-select
              v-model="form.TaskStaffID"
              :disabled="form.QuerenCount > 1"
            >
              <el-option
                v-for="item in staffList"
                :key="item.StaffID"
                :label="item.StaffName"
                :value="item.StaffID"
              />
            </el-select>
          </el-form-item>
        </div>
        <div style="width: 20%; text-align: right; padding: 20px">
          <el-button
            type="primary"
            :disabled="form.QuerenCount > 1"
            @click="save"
          >
            确 定
          </el-button>
          <br />
          <el-button style="margin-top: 15px" @click="close">取 消</el-button>
        </div>
      </el-form>
    </div>
    <div v-if="editType !== 0" style="width: 100%; height: auto">
      <div>
        <el-table
          v-loading="listLoading"
          :data="WorkTaskList"
          @selection-change="setSelectRows"
        >
          <el-table-column
            align="center"
            label="任务内容"
            prop="WorkTaskName"
            show-overflow-tooltip
            width="230"
          />
          <el-table-column
            align="center"
            label="单位"
            prop="WorkTaskUnit"
            show-overflow-tooltip
            width="80"
          />
          <el-table-column
            align="center"
            label="计划数量"
            prop="WorkTaskNum"
            show-overflow-tooltip
          />
          <el-table-column
            align="center"
            label="提成金额"
            prop="TichengMoney"
            show-overflow-tooltip
          />
          <el-table-column
            align="center"
            label="计划完成日期"
            prop="PlanFinishDate"
            show-overflow-tooltip
            width="140"
          />
          <el-table-column
            align="center"
            label="备注"
            prop="WorkTaskMemo"
            show-overflow-tooltip
          />
          <el-table-column
            align="center"
            label="实际完成数量"
            prop="FinishNum"
            show-overflow-tooltip
            width="120"
          />
          <el-table-column
            align="center"
            label="实际完成日期"
            prop="FinishDate"
            show-overflow-tooltip
            width="120"
          />
          <el-table-column align="center" label="查看提交详情" width="150">
            <template #default="{ row }">
              <el-button
                v-if="row.TaskState != 0"
                type="success"
                size="small"
                @click="showSubmit(row)"
              >
                查看提交详情
              </el-button>
            </template>
          </el-table-column>
          <el-table-column
            align="center"
            label="质量审核"
            prop="TaskState"
            width="150"
          >
            <template #default="{ row }">
              <div v-if="row.TaskState == 0">待提交完成</div>
              <div v-else>
                <el-select
                  v-model="row.TaskState"
                  style="width: 130px"
                  :disabled="row.TaskState == 2 && StateAuth == 0"
                  @change="editWorkTask(row)"
                >
                  <el-option label="待审核" :value="1" />
                  <el-option label="已审核通过" :value="2" />
                  <el-option label="未通过" :value="-1" />
                </el-select>
              </div>
            </template>
          </el-table-column>
          <el-table-column
            align="center"
            label="业绩审核状态"
            prop="TaskState"
            width="150"
          >
            <template #default="{ row }">
              <div v-if="row.SubmitCheckState === -1">未通过</div>
              <div
                v-if="
                  row.SubmitCheckState === 0 || row.SubmitCheckState == null
                "
              >
                未审核
              </div>
              <div v-if="row.SubmitCheckState === 1">审核通过</div>
            </template>
          </el-table-column>
          <el-table-column
            align="center"
            label="业绩审核"
            prop="TaskState"
            width="150"
          >
            <template #default="{ row }">
              <el-button
                v-if="row.SubmitList.length > 0"
                type="primary"
                size="small"
                @click="upDialogAudit(row)"
              >
                业绩审核
              </el-button>
              <div v-else>未提交业绩单</div>
            </template>
          </el-table-column>
        </el-table>
      </div>
      <div style="clear: both; margin-top: 20px; width: 100%; height: 100px">
        <el-form ref="taskformRef" :model="taskform" :rules="rules">
          <el-space>
            <el-form-item label="任务内容" prop="WorkTaskSetID">
              <el-select
                v-model="taskform.WorkTaskSetID"
                :disabled="form.QuerenCount > 1"
                style="width: 200px"
                @change="changeWorkTask"
              >
                <el-option
                  v-for="(item, index) in WorkTaskSetOption"
                  :key="index"
                  :label="item.WorkTaskName"
                  :value="item.WorkTaskSetID"
                />
              </el-select>
            </el-form-item>
            <!-- <el-form-item label="单位" prop="WorkTaskUnit">
              <el-select
                v-model="taskform.WorkTaskUnit"
                :disabled="form.QuerenCount > 1"
                style="width: 60px"
              >
                <el-option
                  :disabled="form.QuerenCount > 1"
                  label="个"
                  :value="1"
                />
              </el-select>
            </el-form-item> -->
            <el-form-item label="计划数量" prop="WorkTaskNum">
              <el-input-number
                v-model="taskform.WorkTaskNum"
                :min="0"
                style="width: 120px"
                :disabled="form.QuerenCount > 1"
                @change="handleChange"
              />
              <span style="margin-left: 10px">{{ taskform.WorkTaskUnit }}</span>
            </el-form-item>
            <el-form-item label="计划完成日期" prop="PlanFinishDate">
              <el-date-picker
                v-model="taskform.PlanFinishDate"
                :disabled="form.QuerenCount > 1"
                type="date"
                placeholder="选择日期"
                size="default"
                style="width: 180px"
              />
            </el-form-item>
            <el-form-item label="提成金额" prop="TichengMoney">
              <el-input
                v-model="taskform.TichengMoney"
                type="number"
                placeholder="请输入提成金额"
                :disabled="form.QuerenCount > 1"
                style="width: 150px"
              />
            </el-form-item>
          </el-space>
          <el-space>
            <el-form-item label="任务备注" prop="WorkTaskMemo">
              <el-input
                v-model="taskform.WorkTaskMemo"
                :disabled="form.QuerenCount > 1"
                style="width: 630px"
              />
            </el-form-item>
            <el-form-item>
              <el-button
                :icon="Search"
                type="primary"
                :disabled="form.QuerenCount > 1"
                plain
                @click="editWorkTask"
              >
                确认添加
              </el-button>
            </el-form-item>
          </el-space>
        </el-form>
      </div>
    </div>
    <el-dialog
      v-model="centerDialogVisible"
      title="驳回"
      width="500"
      @close="isClose"
    >
      <div style="margin: 0px 0px 10px 0px">请输入驳回原因</div>
      <div><el-input v-model="taskform.rejectReason" /></div>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="toReject">确认驳回</el-button>
        </div>
      </template>
    </el-dialog>
  </el-dialog>

  <el-dialog
    v-model="dialogAudit"
    title="业绩审核"
    width="1400px"
    @close="logClose"
  >
    <el-table
      v-loading="listLoading"
      :data="SubmitList"
      @selection-change="setSelectRows"
    >
      <el-table-column
        align="center"
        label="任务提交ID"
        prop="TaskSubmitID"
        width="100"
        show-overflow-tooltip
      />
      <el-table-column
        align="center"
        label="添加时间"
        prop="addTime"
        show-overflow-tooltip
      />
      <el-table-column
        align="center"
        label="制作员工"
        prop="MakeStaffName"
        show-overflow-tooltip
      />
      <el-table-column
        align="center"
        label="工种"
        prop="MakeStaffPostName"
        show-overflow-tooltip
      />
      <el-table-column
        align="center"
        label="制作数量"
        prop="FinishNum"
        show-overflow-tooltip
      />

      <el-table-column
        align="center"
        label="提成总金额"
        prop="TichengTotalMoney"
        show-overflow-tooltip
      />
      <el-table-column
        align="center"
        label="提成比例"
        prop="TichengRate"
        show-overflow-tooltip
      />
      <el-table-column
        align="center"
        label="业务提成"
        prop="TichengMoney"
        show-overflow-tooltip
      />
    </el-table>
    <div
      style="
        display: flex;
        align-items: center;
        justify-content: space-between;
        margin-top: 10px;
      "
    >
      <el-form-item label="审核状态" prop="WorkTaskSetID" style="width: 100%">
        <el-select v-model="SubmitCheckState" style="width: 200px">
          <el-option
            v-for="(item, index) in auditOptions"
            :key="index"
            :label="item.label"
            :value="item.value"
          />
        </el-select>
        <div style="display: flex; align-items: center; width: 50%">
          <div style="margin: 0px 10px">审核备注</div>
          <div style="width: 80%">
            <el-input v-model="SubmitCheckMemo" placeholder="请输入审核原因" />
          </div>
        </div>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="SubmitCheck">确认</el-button>
      </el-form-item>
    </div>
    <!-- <template #footer>
      <el-button @click="logClose">取 消</el-button>
      <el-button type="primary" @click="receiveTask">确 定</el-button>
    </template> -->
  </el-dialog>
</template>

<script>
  import {
    AssignStaffSelect,
    OperateCompanySelect,
    OperateDeptmentSelect,
    GetStaffSelect,
  } from '@/api/common'
  import {
    getWorkTaskSet,
    getWorkTaskList,
    saveWorkTask,
    CheckTaskSubmit,
  } from '@/api/worktask'
  import { saveOrderAssign } from '@/api/businessReviewsplitorders'
  import { ElMessage } from 'element-plus'

  export default defineComponent({
    name: 'AssignStaff',
    emits: ['fetch-data'],
    setup(props, { emit }) {
      const $baseMessage = inject('$baseMessage')
      const { fetchData } = inject('rootMethods')

      const state = reactive({
        WorkTaskMsg: {},
        SubmitCheckMemo: '',
        WorkTaskListID: 0,
        SubmitCheckState: 0,
        dialogAudit: false,
        SubmitList: [],
        GiftList: [],
        unitsTitle: '个',
        companyProps: {
          expandTrigger: 'hover',
        },
        deptmentProps: {
          expandTrigger: 'hover',
        },
        flag: false,
        isRules: {
          OrderListID: [
            { required: true, trigger: 'blur', message: '请选择签约产品' },
          ],
          TaskCompany: [
            { required: true, trigger: 'blur', message: '请选择所属组织' },
          ],
          TaskDeptment: [
            { required: true, trigger: 'blur', message: '请选择所属部门' },
          ],
          TaskStaffID: [
            { required: true, trigger: 'blur', message: '请先选择' },
          ],
        },
        organizationList: [],
        staffList: [],
        departmentList: [],
        centerDialogVisible: false,
        OrderID: 0,
        formRef: null,
        form: {
          ProductType: 0,
        },
        title: '',
        dialogFormVisible: false,
        OrderList: [],
        StoreList: [],
        StaffOptions: [],
        auditOptions: [
          {
            value: 0,
            label: '未审核',
          },
          {
            value: 1,
            label: '审核通过',
          },
          {
            value: -1,
            label: '未通过',
          },
        ],
        getStaffParams: [],
        taskformRef: null,
        taskform: {
          TichengMoney: 0,
          WorkTaskNum: 1,
        },
        WorkTaskSetOption: [],
        editType: 0,
        WorkTaskList: [],
        currShowSubmit: {},
        innerVisible: false,
        StateAuth: 0,
      })

      const showEdit = (
        OrderID,
        AssignSet,
        OrderList,
        WorkTask,
        GiftList,
        SaleStaffInfo
      ) => {
        console.log(OrderID, '1')
        console.log(AssignSet, '2')
        console.log(OrderList, '3')
        console.log(WorkTask, '4')
        console.log(GiftList, '5')
        console.log(SaleStaffInfo, '6')

        state.GiftList = GiftList
        state.form = Object.assign({}, WorkTask)
        if (!state.form.ProductType) {
          state.form.ProductType = 0
        }

        console.log(state.form, '123')
        state.title = AssignSet.AssignOrderTargetName
        state.AssignSet = AssignSet
        state.OrderID = OrderID
        state.form.OrderID = OrderID
        // state.OrderList = []
        state.OrderList = OrderList
        if (!state.form.OrderListID) {
          state.form.OrderListID = state.OrderList[0].OrderListID
        }
        state.getStaffParams = AssignSet.AssignOrderTargetIDs
        state.editType = Object.keys(WorkTask).length
        console.log(WorkTask, 'WorkTask.lengthWorkTask.length')

        if (AssignSet.AssignOrderSetID === 1) {
          console.log('AssignSet.AssignOrderSetID', AssignSet.AssignOrderSetID)
          state.form.OrderID = OrderID
          state.form.AssignOrderSetID = AssignSet.AssignOrderSetID
          state.form.TaskCompany = [7]
          getDeptment()
          state.form.TaskDeptment = [7]
          getStaffPost()
          state.form.TaskCompany = 7
        } else if (AssignSet.AssignOrderSetID == 3) {
          // 指派运营师
          const myOrderList = JSON.parse(JSON.stringify(OrderList[0]))
          console.log(myOrderList, 'myOrderList')
          state.form.OrderListID = myOrderList.OrderListID
          state.form.OrderID = myOrderList.OrderID
          state.form.AssignOrderSetID = AssignSet.AssignOrderSetID
          state.flag = true
          if (!state.form.OrderListID) {
            state.form.OrderListID = state.OrderList[0].OrderListID
          }
          if (myOrderList.ServiceCompany) {
            state.form.TaskCompany = JSON.parse(myOrderList.ServiceCompany)
            state.form.TaskDeptment = JSON.parse(myOrderList.ServiceDeptment)
            getDeptment()
          }
        } else if (AssignSet.AssignOrderSetID === 5) {
          state.form.OrderID = OrderID
          state.form.AssignOrderSetID = AssignSet.AssignOrderSetID
          state.form.TaskCompany = [8]
          getDeptment()
          state.form.TaskDeptment = [8, 5, 3]
          getStaffPost()
          state.form.TaskCompany = 8
          state.form.TaskStaffID = 13
        } else if (AssignSet.AssignOrderSetID === 12 && !WorkTask.TaskCompany) {
          // 视频分单到销售人员 的情况下 自动展示本单的销售
          state.form = Object.assign({}, SaleStaffInfo)
          state.form.TaskCompany = JSON.parse(state.form.CompanyID)[0]
          state.form.TaskCompany.shift()
          state.form.TaskDeptment = JSON.parse(state.form.DepartmentID)[0]
          getDeptment()
          state.form.TaskStaffID = state.form.StaffID
          getStaffSelects()
          if (!state.form.ProductType) {
            state.form.ProductType = 0
          }
          if (!state.form.OrderListID) {
            state.form.OrderListID = state.OrderList[0].OrderListID
          }

          // console.log(state.form, '123')
          state.title = AssignSet.AssignOrderTargetName
          state.AssignSet = AssignSet
          state.OrderID = OrderID
          state.form.OrderID = OrderID
          // state.OrderList = []
          state.OrderList = OrderList
          state.getStaffParams = AssignSet.AssignOrderTargetIDs
          state.editType = Object.keys(WorkTask).length
          state.form.AssignOrderSetID = AssignSet.AssignOrderSetID
          console.log(state.form, '  state.form啥呀~！')
        } else {
          state.flag = false
          if (state.form.TaskCompany) {
            state.form.TaskCompany = JSON.parse(WorkTask.TaskCompany)
            state.form.TaskDeptment = JSON.parse(WorkTask.TaskDeptment)
            getDeptment()
          }
          state.form.OrderID = OrderID
          state.form.AssignOrderSetID = AssignSet.AssignOrderSetID
          getStaffSelects()
        }

        if (state.editType === 0) {
          state.form.WorkTaskID = 0
        } else {
          state.editType = WorkTask.isList
          state.taskform.WorkTaskID = WorkTask.WorkTaskID
          state.taskform.WorkTaskListID = 0
          getWorkTaskSets()
          getWorkTaskLists()
        }

        state.dialogFormVisible = true
      }

      const showSubmit = (row) => {
        state.currShowSubmit = row
        state.innerVisible = true
      }
      const SubmitCheck = async () => {
        console.log(state.SubmitList, 'state.审核')
        const dataMsg = {
          WorkTaskListID: state.WorkTaskListID,
          SubmitCheckState: state.SubmitCheckState,
          SubmitCheckMemo: state.SubmitCheckMemo,
        }
        const { msg } = await CheckTaskSubmit(dataMsg)
        $baseMessage(msg, 'success', 'vab-hey-message-success')
        logClose()
        getWorkTaskLists()
        console.log(msg, '123123')
      }

      const upDialogAudit = (row) => {
        state.dialogAudit = true
        state.WorkTaskListID = row.WorkTaskListID
        state.SubmitList = row.SubmitList
        state.SubmitCheckState = row.SubmitCheckState
        console.log(row, '点击的那个')
      }

      const close = () => {
        state['formRef'].resetFields()
        emit('fetch-data')
        state.form = {
          ProductType: 0,
        }
        state.taskform = {
          WorkTaskListID: 0,
          TichengMoney: 0,
        }

        state.OrderList = []
        state.WorkTaskList = []
        state.staffList = []
        state.departmentList = []
        state.dialogFormVisible = false
      }

      const isClose = () => {
        state.taskform.saveWorkTask = ''
        state.taskform = {
          WorkTaskID: state.taskform.WorkTaskID,
          WorkTaskListID: 0,
          TichengMoney: 0,
        }
        getWorkTaskLists()
      }

      const toReject = async () => {
        if (!state.taskform.rejectReason) {
          ElMessage({
            message: '驳回理由不能为空！',
            type: 'warning',
          })
        } else {
          const { msg } = await saveWorkTask(state.taskform)
          $baseMessage(msg, 'success', 'vab-hey-message-success')
          state.taskform.rejectReason = ''
          state.taskform = {
            WorkTaskID: state.taskform.WorkTaskID,
            WorkTaskListID: 0,
          }
          getWorkTaskLists()
          state.centerDialogVisible = false
        }
      }

      const editWorkTask = (row) => {
        if (row.WorkTaskListID) {
          state.taskform = Object.assign({}, row)
          state.taskform.TrackState = 1
        }

        console.log('state.taskform', state.taskform)
        state['taskformRef'].validate(async (valid) => {
          if (valid) {
            if (row.TaskState == -1) {
              state.centerDialogVisible = true
              return
            }
            const { msg } = await saveWorkTask(state.taskform)
            $baseMessage(msg, 'success', 'vab-hey-message-success')
            state['taskformRef'].resetFields()
            state.taskform = {
              WorkTaskID: state.taskform.WorkTaskID,
              WorkTaskListID: 0,
              TichengMoney: 0,
            }
            fetchData()
            getWorkTaskLists()
          }
        })
      }

      const save = () => {
        state['formRef'].validate(async (valid) => {
          if (valid) {
            const { msg } = await saveOrderAssign(state.form)
            $baseMessage(msg, 'success', 'vab-hey-message-success')
            fetchData()
            close()
          }
        })
      }

      const changeWorkTask = (row) => {
        const res = state.WorkTaskSetOption.find((item) => {
          return item.WorkTaskSetID == row
        })
        state.WorkTaskMsg = res
        state.taskform.WorkTaskUnit = res.WorkTaskUnit
        state.taskform.TichengMoney =
          Number(res.TichengPrice) * Number(state.taskform.WorkTaskNum)
      }
      const handleChange = () => {
        if (state.WorkTaskMsg) {
          state.taskform.TichengMoney =
            Number(state.WorkTaskMsg.TichengPrice) *
            Number(state.taskform.WorkTaskNum)
        }
      }

      const getWorkTaskLists = async () => {
        state.listLoading = true
        const getParams = {
          WorkTaskID: state.form.WorkTaskID,
        }
        const {
          data: { StateAuth, WorkTaskList },
        } = await getWorkTaskList(getParams)
        state.WorkTaskList = WorkTaskList
        state.StateAuth = StateAuth
        state.listLoading = false
      }

      const getStaffSelects = async () => {
        state.listLoading = true
        const getStaffParams = {
          AssignOrderSetID: state.AssignSet.AssignOrderSetID,
          OrderID: state.OrderID,
          StaffPostID: state.getStaffParams,
        }
        const {
          data: { StaffOptions },
        } = await AssignStaffSelect(getStaffParams)
        state.StaffOptions = StaffOptions
        state.staffList = StaffOptions
        state.listLoading = false
      }

      const getWorkTaskSets = async () => {
        state.listLoading = true
        const getParams = {
          AssignOrderSetID: state.form.AssignOrderSetID,
          WorkTaskID: state.form.WorkTaskID,
        }
        const {
          data: { WorkTaskSetOption },
        } = await getWorkTaskSet(getParams)
        state.WorkTaskSetOption = WorkTaskSetOption
        state.listLoading = false
      }
      // 获取运营组织
      const getOrganization = async () => {
        const { data } = await OperateCompanySelect()
        console.log(data, '获取组织')
        state.organizationList = data.CompanyOptions
      }
      // 获取部门
      const getDeptment = async () => {
        const dataMsg = {
          CompanyID: state.form.TaskCompany[state.form.TaskCompany.length - 1],
        }
        const { data } = await OperateDeptmentSelect(dataMsg)

        state.departmentList = data.DeptmentOptions

        if (state.form.TaskDeptment) {
          getStaffPost()
        }
      }
      // 获取员工
      const getStaffPost = async () => {
        console.log('state.form.TaskDeptment', state.form.TaskDeptment)
        let dataMsg = {}
        if (typeof state.getStaffParams == 'string') {
          dataMsg = {
            Deptment: [state.form.TaskDeptment],
            StaffPostID: JSON.parse(state.getStaffParams),
          }
        } else {
          dataMsg = {
            Deptment: [state.form.TaskDeptment],
            StaffPostID: state.getStaffParams,
          }
        }

        const { data } = await GetStaffSelect(dataMsg)

        state.staffList = data.StaffPostOptions
      }
      const logClose = () => {
        state.dialogAudit = false
      }
      onMounted(() => {
        getOrganization()
      })

      return {
        ...toRefs(state),
        showEdit,
        logClose,
        getStaffPost,
        close,
        getOrganization,
        isClose,
        SubmitCheck,
        save,
        changeWorkTask,
        getWorkTaskSets,
        getDeptment,
        editWorkTask,
        showSubmit,
        handleChange,
        toReject,
        upDialogAudit,
      }
    },
  })
</script>
<style>
  .htmlBox img {
    width: 100%;
  }
</style>
